import _ from 'lodash'
import dataObjectConf from './data-object-conf.js'
import emitter from '../../../mixins/emitter'

export const getUiItemExtraForEditable = context => {
  const { editable, selected, id } = context.props
  const extra = {
    'class': {},
    nativeOn: {},
    key: id
  }
  if (editable) {
    extra.class['zlst-ui-item-wrapper'] = true
    extra.nativeOn.click = evt => {
      emitter.methods.dispatch('MainBoard', 'widget-selected', [id], context)
      evt.stopPropagation()
    }
    if (selected) {
      extra.class['is-active'] = true
    }
  }
  return extra
}

export const getUiItemDataObject = context => {
  const { setting } = context.props
  const extra = getUiItemExtraForEditable(context)
  return _.merge({}, dataObjectConf, {
    props: {
      label: setting.options.name,
      required: setting.options.required
    }
  }, extra)
}

export const generateOperateButtons = (h, context) => {
  const commonDataObject = {
    props: { shape: 'circle' }
  }
  const buttons = [
    h('Button', _.merge({}, commonDataObject, {
      props: { icon: 'md-copy', type: 'primary' },
      attrs: { role: 'copy' },
      on: {
        click: evt => {
          emitter.methods.dispatch('MainBoard', 'widget-copy', [context.props.id], context)
          // 禁止冒泡
          evt.stopPropagation()
        }
      }
    })),
    h('Button', _.merge({}, commonDataObject, {
      props: { icon: 'md-trash', type: 'warning' },
      attrs: { role: 'delete' },
      on: {
        click: evt => {
          emitter.methods.dispatch('MainBoard', 'widget-delete', [context.props.id], context)
          // 禁止冒泡
          evt.stopPropagation()
        }
      }
    })),
  ]
  return buttons
}

export const buttonAssociationHandler = (context, event) => {
  emitter.methods.dispatch(
    'MainBoard',
    'button-association-handler',
    ['参数associatedEvent', event],
    context
  )
}

export const getIdentificationDataObject = (h, context) => {
  const { setting } = context.props
  const commonDataObject = {
    props: { value: false }
  }
  const checkbox = [
    h('Checkbox', _.merge({}, commonDataObject, {
      style: {
        position: 'absolute',
        right: '-16px',
        zIndex: 999,
        top: '-12px',
      },
      on: {
        'on-change': (value) => {
          if(value){
            emitter.methods.dispatch('MainBoard', 'markSelect-add', [context.props.index], context)
          } else {
            emitter.methods.dispatch('MainBoard', 'markSelect-delete', [context.props.index], context)
          }
        }
      }
    }))
  ]
  return checkbox
}
